package com.wmzdq.security;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.security.web.util.UrlUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by sunjian on 15/5/13.
 */
public class ForceHttpsRedirectStrategy implements RedirectStrategy {
    protected final Log logger = LogFactory.getLog(getClass());

    private static boolean forceHttps;

    static {
        forceHttps = Boolean.valueOf(System.getProperty("forceHttps", "false"));
    }

    @Override
    public void sendRedirect(HttpServletRequest request, HttpServletResponse response, String url) throws IOException {
        String redirectUrl = calculateRedirectUrl(request.getServerName(), request.getContextPath(), url);
        redirectUrl = response.encodeRedirectURL(redirectUrl);

        if (logger.isDebugEnabled()) {
            logger.debug("Redirecting to '" + redirectUrl + "'");
        }

        response.sendRedirect(redirectUrl);
    }

    private String calculateRedirectUrl(String serverName, String contextPath, String url) {
        if (!UrlUtils.isAbsoluteUrl(url)) {
            if (forceHttps) {
            	String redirtUrl = "https://" + serverName + contextPath + url; 
                return redirtUrl;
            } else {
                return contextPath + url;
            }
        }

        if (!forceHttps) {
            return url;
        }
        url = url.substring(url.lastIndexOf("://") + 3); // strip off scheme


        return "https://" + url;
    }
}
